package com.bw.livepush;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class WebSocketService extends Service {

    private WebSocket webSocket;
    private long retryTime = 10*1000;//10s重连
    private MsgCallBack callBack;//livepushactivity实现回调接口，
    // service通过回调接口将后台接受到消息传递给服务器

    //设置回调接口方法
    public void setCallBack(MsgCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        connectWebSocket();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new WebSocketBinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWebSocket();
    }

    private void connectWebSocket(){
        Request.Builder builder = new Request.Builder();
        builder.url(LiveConst.WEBSOCKETURL);
        Request request = builder.build();
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        clientBuilder.pingInterval(10, TimeUnit.SECONDS);//设置间隔10s ping服务器ws连接
        webSocket = clientBuilder.build().newWebSocket(request,listener);
    }

    private WebSocketListener listener = new WebSocketListener(){

        @Override
        public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
            super.onOpen(webSocket, response);
            //开启
            try {
                Log.e("ZXY","onOpen:"+response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
            super.onClosed(webSocket, code, reason);
            //关闭
        }

        @Override
        public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
            super.onMessage(webSocket, text);
            //接收服务器push下来得消息
            if (text.equals("连接成功")){
                Log.e("ZXY","onMessage:连接到websocket服务器");
                return;
            }
            int type = 0;
            try {
                JSONObject jsonObject = new JSONObject(text);
                type = jsonObject.getInt("type");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MsgEntity entity = null;
            if (type == 0){
                TxtMsgEntity txtMsgEntity = new Gson().fromJson(text,TxtMsgEntity.class);
                entity = txtMsgEntity;
            }else if (type == 1){
                PopMsgEntity popMsgEntity = new Gson().fromJson(text,PopMsgEntity.class);
                entity = popMsgEntity;
            }else if (type == 2){
                GiftMsgEntity giftMsgEntity = new Gson().fromJson(text,GiftMsgEntity.class);
                entity = giftMsgEntity;
            }
            Message msg = handler.obtainMessage();
            msg.what = 100;
            msg.obj = entity;
            handler.sendMessage(msg);
        }

        @Override
        public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @org.jetbrains.annotations.Nullable Response response) {
            super.onFailure(webSocket, t, response);
            //连接异常->重连
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //连接异常断开重连ws服务器
                    connectWebSocket();
                }
            },10*1000);
        }
    };

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MsgEntity msgEntity = (MsgEntity) msg.obj;
            callBack.msgCall(msgEntity);
        }
    };

    private void closeWebSocket(){
        if (webSocket!=null)
            webSocket.close(0,"close");
    }


    public class WebSocketBinder extends Binder{

        public WebSocketService getWebSocketService(){
            return WebSocketService.this;
        }

    }


}
